package com.gjt.InternetAddress;

import com.gjt.InternetAddress.thread.LookupTask;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.*;

/**
 * Created with Intel IDEA.
 * 解析web日志文件，找出ip 并获取主机名 写入 hello.txt
 *
 *
 * @Auther: gjt
 * @Date: 2024/3/21 21:16
 */
public class PoolWebLog {
    private final static int NUM_THREADS = 4;

    public static void main(String[] args) throws IOException {

//        ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS, new ThreadPoolFactory("weblogThread"));
        ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS);
        Queue<LogEntry> result = new LinkedList<>();

        try(BufferedReader buf= new BufferedReader(
                new InputStreamReader(Files.newInputStream(Paths.get("C:\\Users\\23152\\Desktop\\requests.log"))))){
            for(String entry = buf.readLine();entry != null; entry = buf.readLine()){
                LookupTask lookupTask = new LookupTask(entry);
                Future<String> submit = executorService.submit(lookupTask);
                LogEntry logEntry = new LogEntry(entry, submit);
                result.add(logEntry);
            }
        }catch (IOException e){
            e.printStackTrace();
        }

        for (LogEntry logEntry : result) {
            try(BufferedWriter bufferedWriter = new BufferedWriter(
                    // 可以向文件中追加内容
                    new FileWriter("C:\\Users\\23152\\Desktop\\hello.txt",true))) {
                bufferedWriter.write(logEntry.future.get());
                bufferedWriter.write("\n\r");
                bufferedWriter.flush();
            }catch (IOException|ExecutionException | InterruptedException  e){
                e.printStackTrace();
            }
        }
        executorService.shutdown();
    }

    private static class LogEntry{
        String original;
        Future<String> future;

        public LogEntry(String original, Future<String> future) {
            this.original = original;
            this.future = future;
        }
    }
}
